/*
 * @Author: CodeHare
 * @Date: 2023-09-19 18:46:23
 * @LastEditors: yangni 920556271@qq.com
 * @LastEditTime: 2024-03-10 16:55:35
 * @Description: 我的页面
 * 
 */
// ignore_for_file: prefer_typing_uninitialized_variables
import 'dart:developer';
import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_scalable_ocr/flutter_scalable_ocr.dart';
import 'package:get/get.dart';
import 'package:google_mlkit_text_recognition/google_mlkit_text_recognition.dart';
import 'package:native_dart_package/http/request/exception/exception_handler.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/pages/mine/mine/mine_model.dart';
import 'package:yt_devops/pages/mine/mine/recognize_page.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/services/auth/auth_services.dart';
import 'package:yt_devops/user_entity_manager.dart';
import 'package:yt_devops/utils/constants/permission_page_constant.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:path_provider/path_provider.dart';
import 'package:yt_devops/utils/extensions.dart';
import 'package:yt_devops/utils/func_utils.dart';

class MineController extends GetxController {
  MineState state = MineState();
  final _authServices = Get.put(AuthServices());
  var userModel;
  int roleId = RoleType.owner.value;
  final textRecognizer = TextRecognizer(script: TextRecognitionScript.latin);
  List allItems = [
    {
      "icon": ImageAssets.mineInfoCenter,
      "title": ResKey.messageCenter,
      "onTap": () {
        Get.toNamed(RouterPath.messageCenter);
      },
      "auth": PermissionConstant.mineMessageCenter,
    },
    {
      "icon": ImageAssets.mineUserManage,
      "title": ResKey.userMangement,
      "onTap": () {
        Get.toNamed(RouterPath.userManage);
      },
      "auth": PermissionConstant.mineUserManage,
    },
    {
      "icon": ImageAssets.mineAlarmReportManage,
      "title": ResKey.faultReportManagement,
      "onTap": () {
        Get.toNamed(RouterPath.faultReportList);
      },
      "auth": PermissionConstant.mineFaultReportManage,
    },
    {
      "icon": ImageAssets.mineHelp,
      "title": ResKey.helpAndFeedBack,
      "onTap": () {
        Get.toNamed(RouterPath.suggestion);
      },
      "auth": PermissionConstant.mineHelpFeedback,
    },
    {
      "icon": ImageAssets.mineAboutUs,
      "title": ResKey.aboutUs,
      "onTap": () {
        Get.toNamed(RouterPath.aboutUs);
      },
      "auth": PermissionConstant.mineAboutUs,
    },
    {
      "icon": ImageAssets.mineSystemSettings,
      "title": ResKey.systemSetting,
      "onTap": () {
        Get.toNamed(RouterPath.systemSettings);
      },
      "auth": PermissionConstant.mineSystemSetting,
    }
  ];
  List topItems = [];
  List bottomItems = [];

  @override
  void onInit() {
    super.onInit();
    Log.d('MinePage==1111');
    getUserDetails();
  }

  String formatPhone(phone) {
    if (phone == null || phone.length == 0) {
      phone = "****";
    } else if (phone.length >= 11) {
      phone = phone.replaceRange(3, 7, '****');
    }

    return phone;
  }

  void getUserDetails() async {
    Configs.httpClient.requestWithLoading(() async {
      await _authServices.getUserInfo().then((value) {
        userModel = UserModel.fromJson(value);
        state = MineState.fromMap(value);

        /// 角色
        roleId = userModel.roles[0].roleId;
        getItemsByRoleId(roleId);
        update();
      });

      /// 缓存个人信息
      UserEntityManager().save(userModel
        ..password = UserEntityManager().userModel.password
        ..loginedAccount = UserEntityManager().userModel.loginedAccount);
    }, onError: (err) {
      // dismissLoading();
      handleException(err);
      return true;
    }, showLoading: false);
  }

  void goMessageCenter() {
    Get.toNamed(RouterPath.messageCenter);
  }

  ///用户管理页面

  void goUserManage() {
    Get.toNamed(RouterPath.userManage);
  }

  ///用户个人信息

  void gotoUserInfo() {
    Get.toNamed(RouterPath.userInfoPage)?.then((value) {
      Log.d('value==' + value.toString());
      if (value != null) {
        state.nickName = value['nickName'];
        state.phone = value['phone'];
        state.avatar = value['avatar'];
        state.email = value['email'];
        update();
      }
    });
  }

  void goFaultReportManage() {
    /// 此处跳转到报账单模块
    print("报账单模块");
    Get.toNamed(RouterPath.faultReportList);
    // Get.toNamed(RouterPath.reportTaskDetail, arguments: {
    //   'id': 84,
    // });
  }

  void goHelpFeedBack() {
    Get.toNamed(RouterPath.suggestion);
  }

  void goAboutUs() {
    Get.toNamed(RouterPath.aboutUs);
  }

  recognizeText() async {
    Navigator.push(
      Get.context!,
      MaterialPageRoute(
        builder: (context) => const RecognizePage(
          title: '文字识别',
        ),
      ),
    );
    // File file = await _getLocalFile();
    // if(file!= null){
    //   Log.d('file==' + file.length().toString());
    // }
    // Log.d('localePath==' + localePath.toString());

    // InputImage inputImage = InputImage.fromFilePath('/Users/liuer/Desktop/yongtai/yt_devop_app/assets/images/site/text.png');
    // final RecognizedText recognizedText = await textRecognizer.processImage(inputImage);
    //
    // String text = recognizedText.text;
    // for (TextBlock block in recognizedText.blocks) {
    //   final Rect rect = block.boundingBox;
    //   final List<Point<int>> cornerPoints = block.cornerPoints;
    //   final String text = block.text;
    //   final List<String> languages = block.recognizedLanguages;
    //   Log.d('text==' + text.toString());
    //   for (TextLine line in block.lines) {
    //     // Same getters as TextBlock
    //     for (TextElement element in line.elements) {
    //       // Same getters as TextBlock
    //       Log.d('element==' + element.text.toString());
    //     }
    //   }
    // }
  }

  Future<File> _getLocalFile() async {
    // get the path to the document directory.
    String dir = (await getApplicationDocumentsDirectory()).path;
    Log.d('dir==' + dir.toString());
    return File('$dir/assets/images/site/text.jpg');
  }

  void goSystemSettings() {
    Get.toNamed(RouterPath.systemSettings);
  }

  getItemsByRoleId(int id) {
    topItems.clear();
    bottomItems.clear();
    allItems.forEachIndexed((element, index) {
      if (FuncUtils.isPassAuthority([element["auth"]])) {
        if (index != 2 || id == RoleType.owner.value) {
          if (index < 4) {
            topItems.add(element);
          } else {
            bottomItems.add(element);
          }
        }
      }
    });
  }
}
